<?php
namespace App\Admin\Forms\Money;

use App\Models\User;
use App\Models\UserMoney;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Traits\LazyWidget;
use Illuminate\Support\Facades\DB;
use Dcat\Admin\Contracts\LazyRenderable;

class UserMoneyForm extends Form implements LazyRenderable
{
    use LazyWidget;


    public function handle(array $input)
    {
        // 接收外部传递参数
        $user_id = $this->payload['user_id'] ?? 0;
        $user = User::find($user_id);
        if($input){
            if(!$input['money']){
                return $this->response()->error('请输入大于0的数额!');
            }
            $type = $input['type'];
            if($type){
                //余额扣除
                if($user->money<$input['money']){
                    return $this->response()->error('当前用户积分不足以扣除!');
                }
                $money = -floatval($input['money']);
                $title = "扣减余额";
            }else{
                $money = floatval($input['money']);
                $title = "新增余额";
            }
            DB::transaction(function() use ($type,$user_id,$money, $title) {
                UserMoney::money($type?2:1,$user_id,$money,$title);
            });
            return $this->response()->success($title."成功!")->refresh();
        }
        return $this->response()->success('暂无修改');
    }

    public function form()
    {
        $user_id = $this->payload['user_id'] ?? 0;
        $user = User::find($user_id);
        $this->display('current_money','当前用户余额')->default($user->money);
        $this->radio('type','修改类型')->options(['新增余额','扣减余额'])->default(0);
        $this->number('money','变更余额')->default(0);

    }
}
